<!--
 * @Description: 结算单管理
 * @Author: py
 * @Date: 2024-12-19
-->
<script setup lang="ts" name="settlement-list">
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { hasPermi } from '@fl/utils/has-permi'
import { useUserStoreWithOut } from '@fl/store/modules/user'
import { dictListApi, settleOrderListApi, useSettleOrderList } from '@fl/api/charge-settle'
import { SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import { useDicts } from './hooks/use-dicts'

const router = useRouter()

const userStore = useUserStoreWithOut()
const enterpriseId = userStore.getOrgInfo?.enterpriseId ?? ''
const enterpriseTypeName = userStore.getOrgInfo?.enterpriseTypeName ?? ''
// 判断是否为设备商
const isEquipSupplier = computed(() => enterpriseTypeName === '设备商(清分业务)')

const { getDictLabel, getDictOptions } = useDicts()

type DictItem = {
    dictType: string
    dictValue: string | number
    dictLabel: string
}

const dictList = ref<DictItem[]>([])
const vendorOptions = computed(() => {
    return dictList.value
        .filter(item => item.dictType === 'charge_vendor_type')
        .map(item => ({
            label: item.dictLabel,
            value: item.dictValue,
        }))
})
const settleStatusOptions = getDictOptions('oSettleStatus')

function getDictionaryDatas() {
    dictListApi({
        pageNum: 1,
        pageSize: 99999,
    }).then((res) => {
        dictList.value = res || []
    })
}
getDictionaryDatas()

const initialState = {
    vendorId: isEquipSupplier.value ? enterpriseId : '',
    settlementCodeOrName: '',
    settlementDate: null,
    settlementStatus: '',
}

const queryState = ref(cloneDeep(initialState))
const tempState = ref(cloneDeep(queryState))

const queryColumns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            placeholder: '请输入',
        },
        label: '结算单号/名称',
        labelWidth: 108,
        prop: 'settlementCodeOrName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            placeholder: '请选择',
        },
        label: '合作商名称',
        labelWidth: 90,
        options: vendorOptions,
        prop: 'vendorId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 5,
        },
        fieldProps: {
            placeholder: '请选择',
        },
        label: '结算状态',
        labelWidth: 75,
        options: settleStatusOptions.value,
        prop: 'settlementStatus',
        valueType: 'select',
    },
    {
        colProps: {
            span: 7,
        },
        fieldProps: {
            endPlaceholder: '结束日期',
            format: 'YYYY-MM-DD',
            startPlaceholder: '开始日期',
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        label: '结算日期',
        labelWidth: 75,
        prop: 'settlementDate',
        valueType: 'date-picker',
    },
]

if (isEquipSupplier.value) {
    queryColumns.splice(1, 1)
}

const stateMap = {
    1: 'tag-red',
    2: 'tag-orange',
    3: 'tag-orange',
    4: 'tag-blue',
    5: 'tag-green',
}
function formatPrice({ cellValue }) {
    if (cellValue === null) {
        return ''
    }

    return cellValue === 0 ? '¥ 0' : `¥ ${Number.parseFloat(cellValue).toFixed(2)}`
}

const gridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columnConfig: {
        resizable: false,
    },
    columns: [
        { fixed: 'left', field: 'settlementCode', minWidth: 140, title: '结算单号' },
        { field: 'settlementName', minWidth: 250, title: '结算单名称' },
        { field: 'settlementDate', title: '结算日期', width: 110 },
        { field: 'operatorName', minWidth: 130, title: '运营商名称' },
        { field: 'vendorName', minWidth: 160, title: '合作商名称' },
        { field: 'settlementTime', title: '结算时间', width: 160 },
        { slots: { default: 'status' }, title: '结算状态', width: 135 },
        { align: 'right', field: 'totalAmount', formatter: formatPrice, title: '实收总金额', width: 120 },
        { align: 'right', field: 'platformServiceFee', formatter: formatPrice, title: '平台技术服务费', width: 135 },
        { align: 'right', field: 'parkingFee', formatter: formatPrice, title: '停车费申诉扣减费', width: 145 },
        { align: 'right', field: 'revenue', formatter: formatPrice, title: '营业额', width: 120 },
        { align: 'right', field: 'commission', formatter: formatPrice, title: '佣金', width: 120 },
        { align: 'right', field: 'dueSettlementAmount', formatter: formatPrice, title: '应结算金额', width: 120 },
        { align: 'right', field: 'actualSettlementAmount', formatter: formatPrice, title: '实际结算金额', width: 120 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 105 },
    ],
    // headerCellClassName: 'table-header-cell',
    // headerRowClassName: 'bg-white',
    maxHeight: 370,
    rowConfig: {
        isHover: true,
        keyField: 'id',
    },
    showOverflow: false,
})

const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
// const isLoading = ref(false)

const tableData = ref([])
const params = computed(() => ({
    asc: false,
    orderByColumn: 'settlementDate',
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...queryState.value,
    settlementTimeStart: queryState.value.settlementDate?.[0],
    settlementTimeEnd: queryState.value.settlementDate?.[1],
}))
const { data, isLoading, refetch } = useSettleOrderList(params)
watchEffect(() => {
    if (data.value) {
        const { records, total } = data.value
        tablePage.value.total = +total
        tableData.value = cloneDeep(records)
    }
})

/**
function getList() {
    isLoading.value = true

    const { settlementCodeOrName, settlementDate, settlementStatus, vendorId } = queryState.value
    const oParams = {
        asc: false,
        orderByColumn: 'settlementDate',
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
        settlementCodeOrName,
        vendorId,
        settlementStatus,
        settlementTimeStart: settlementDate?.[0],
        settlementTimeEnd: settlementDate?.[1],
    }

    settleOrderListApi(oParams).then((res) => {
        const { records, total } = res
        tablePage.value.total = +total
        tableData.value = records
    }).finally(() => {
        isLoading.value = false
    })
}
getList()
*/

function handleSearch() {
    queryState.value = cloneDeep(tempState.value)
    tablePage.value.currentPage = 1
    // getList()
    refetch()
}
function handleReset() {
    queryState.value = cloneDeep(initialState) // 重置过滤条件
    tempState.value = cloneDeep(initialState) // 同步表单
    // 重置分页
    tablePage.value.currentPage = 1
    tablePage.value.pageSize = 10
    // getList()
    refetch()
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    // getList()
    refetch()
}

function toForm(oRaw, type) {
    router.push({
        name: 'settlement-form',
        query: {
            formType: type,
            id: oRaw.id,
        },
    })
}
</script>

<template>
    <ElCard shadow="never"
            class="mb-20 border-none"
    >
        <PlusForm v-model="tempState"
                  :columns="queryColumns"
                  :row-props="{ gutter: 20 }"
                  label-position="right"
        >
            <template #footer>
                <div class="ml-auto">
                    <ElButton type="primary"
                              @click="handleSearch"
                    >
                        搜索
                    </ElButton>

                    <ElButton @click="handleReset">
                        重置
                    </ElButton>
                </div>
            </template>
        </PlusForm>
    </ElCard>

    <ElCard shadow="never"
            class="border-none"
    >
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="tableData"
                     @page-change="handlePageChange"
        >
            <template #status="{ row }">
                <span class="status-tag"
                      :class="stateMap[row.settlementStatus]"
                >
                    {{ getDictLabel('oSettleStatus', row.settlementStatus) }}
                </span>
            </template>

            <template #operate="{ row }">
                <div class="row-btns">
                    <template v-if="row.settlementStatus !== 5">
                        <span v-if="(row.settlementStatus === 1 || row.settlementStatus === 3) && hasPermi('结算单管理-运营商确认')"
                              class="btn-operate"
                              @click="toForm(row, 'operatorConfirm')"
                        >
                            确认
                        </span>

                        <!-- <span v-if="(row.settlementStatus === 1 || row.settlementStatus === 2) && hasPermi('结算单管理-设备商确认')"
                              class="btn-operate"
                              @click="toForm(row, 'vendorConfirm')"
                        >
                            确认
                        </span> -->

                        <span v-if="row.settlementStatus === 4 && hasPermi('结算单管理-结算')"
                              class="btn-operate"
                              @click="toForm(row, 'settle')"
                        >
                            结算
                        </span>
                    </template>

                    <span class="btn-operate"
                          @click="toForm(row, 'detail')"
                    >
                        查看
                    </span>
                </div>
            </template>
        </SearchTable>
    </ElCard>
</template>

<style lang="less" scoped>
@import '../custom.less';
</style>
